package com.intramirror.wd.service.security.auth.token;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 跳过请求匹配路径
 * 
 * @author mars
 *
 * @time 2017-05-25
 */
public class SkipPathRequestMatcher implements RequestMatcher {
	private OrRequestMatcher matchers;
	private List<RequestMatcher> processingMatchers;
	
	/**
	 * @param paths 拦截的路径
	 */
	public SkipPathRequestMatcher(List<String> paths) {
		Assert.notNull(paths, "路径不能为空");
		matchers = new OrRequestMatcher(paths.stream().map(AntPathRequestMatcher::new).collect(Collectors.toList()));
	}
	
	/**
	 * 暂不支持
	 * @param pathsToSkip 不拦截路径
	 * @param paths 拦截路径
	 */
	public SkipPathRequestMatcher(List<String> pathsToSkip, List<String> paths) {
		Assert.notNull(paths, "路径不能为空");
		List<RequestMatcher> m = paths.stream().map(AntPathRequestMatcher::new).collect(Collectors.toList());
		matchers = new OrRequestMatcher(m);
		if(CollectionUtils.isNotEmpty(pathsToSkip))
		{
			processingMatchers = new ArrayList<>();
			pathsToSkip.forEach(req->{
				processingMatchers.add(new AntPathRequestMatcher(req));
			});
		}
		
	}

	public boolean matchesSkipPath(HttpServletRequest request){
		for (RequestMatcher req : processingMatchers) {
			if(req.matches(request))return true;
		}
		return false;
	}

	@Override
	public boolean matches(HttpServletRequest request) {
		/*for (RequestMatcher req : processingMatchers) {
			if(req.matches(request))return false;
		}*/
		return matchers.matches(request);
//		if (matchers.matches(request)) {
//			return false;
//		}
//		for (RequestMatcher req : processingMatchers) {
//			if(req.matches(request))return true;
//		}
//		return false;
	}
}
